package net.dodoman.xml;

import java.io.OutputStreamWriter;

import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * 
 * @author yanping
 * 
 */
public class XmlOperator extends DefaultHandler {

	private Locator locator;
	private int index1 = 0;
	private int index2 = 0;

	public static void main(String[] args) {

	}

	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// System.out.print( "SAX Event: CHARACTERS[ " );
		System.out.print("本书<<");
		try {
			OutputStreamWriter outw = new OutputStreamWriter(System.out);
			outw.write(ch, start, length);
			outw.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(">>的目录");
		// System.out.println( " ]" );
	}

	public void endDocument() throws SAXException {
		System.out.println("解析结束：");
	}

	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// System.out.println( "SAX Event: END ELEMENT[ " + localName + " ]" );
		// this.index2=0;
		if (qName.equalsIgnoreCase("chapter"))
			this.index2 = 0;
	}

	public void setDocumentLocator(Locator locator) {
		this.locator = locator;
	}

	public void startDocument() throws SAXException {
		System.out.println("解析开始: ");
	}

	public void startElement(String uri, String localName, String qName,
			Attributes atts) throws SAXException {
		// System.out.println( "SAX Event: START ELEMENT[ " + localName + " ]"
		// );
		if (qName.equalsIgnoreCase("chapter")) {
			index1++;
			for (int i = 0; i < atts.getLength(); i++) {
				// System.out.println(atts.getLength());
				String attName = atts.getQName(i);
				if (attName.equalsIgnoreCase("title")) {
					System.out.println("第" + index1 + "章：" + atts.getValue(i));
				}
			}
		}
		if (qName.equalsIgnoreCase("topic")) {
			index2++;
			for (int i = 0; i < atts.getLength(); i++) {
				String attName = atts.getQName(i);
				if (attName.equalsIgnoreCase("name")) {
					System.out.println("     第" + index2 + "部分："
							+ atts.getValue(i));
				}
			}
		}
	}

}
